﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data.Linq;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Phone.Reactive;
using WP8DataModel.Model;

namespace WP8DataModel.ViewModel
{
    sealed public class BackgroundScheduleModel
    {
        public static readonly string DefaultDbConnectionString = "Data Source=isostore:/BackgroundSchedule.sdf";
        private BackgroundScheduleDataContext _db;

        public BackgroundScheduleModel(string iConnectionString)
        {
            _db = new BackgroundScheduleDataContext(iConnectionString);
            if (!_db.DatabaseExists())
            {
                _db.CreateDatabase();
            }
        }

        // Write changes in the data context to the database.
        public void SaveChangesToDb()
        {
            _db.SubmitChanges();
        }


        public void Dispose()
        {
            _db.Dispose();
            _db = null;
        }

        public async Task<ObservableCollection<BackgroundScheduledTransferItem>> GetTransfersStatus()
        {
            return new ObservableCollection<BackgroundScheduledTransferItem>(_db.BackgroundScheduleItems.Where(item=> item.DownloadLater).OrderBy(item => item.StopTime));
        }

        public void Delete(IEnumerable<BackgroundScheduledTransferItem> iItemsToDelete)
        {
            _db.BackgroundScheduleItems.DeleteAllOnSubmit(iItemsToDelete);
            _db.SubmitChanges(ConflictMode.ContinueOnConflict);
        }

        public BackgroundScheduledTransferItem Fetch(int iShowId)
        {
            return _db.BackgroundScheduleItems.FirstOrDefault(item => item.ShowId == iShowId);
        }

        public void Append(BackgroundScheduledTransferItem aItem)
        {
            _db.BackgroundScheduleItems.InsertOnSubmit(aItem);
        }

        public void SubmitChanges()
        {
            _db.SubmitChanges(ConflictMode.ContinueOnConflict);
        }

        private static BackgroundScheduleModel _instance;

        public static BackgroundScheduleModel Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new BackgroundScheduleModel(DefaultDbConnectionString);
                }
                return _instance;
            }
        }

        public static void DestroySingleton()
        {
            if (_instance != null)
            {
                _instance.Dispose();
                _instance = null;
            }
        }
    }
}
